package com.dog.controller.system;

import com.dog.common.core.domain.R;
import com.dog.common.utils.wx.WxUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;

/**
 * @program: dog
 * @description:
 * @author: @Dog_Elder
 * @create: 2021-03-13 16:26
 **/
@RestController
//@Log4j2
public class DemoController {

    @GetMapping("index")
    public ResponseEntity<String> index() {
        return ResponseEntity.ok("请求成功");
    }

    @GetMapping("page")
    public ModelAndView page() {
        return new ModelAndView("websocket");
    }

    @RequestMapping("/push/{toUserId}")
    public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId) throws IOException {
        WebSocketServer.sendInfo(message, toUserId);
        return ResponseEntity.ok("MSG SEND SUCCESS");
    }

    @Autowired
    private WxUtils wxUtils;

    /**
     * 前端向服务器获取微信的code
     */
    @GetMapping("/getWxCode")
    public void getWxCode(HttpServletResponse response) {
        wxUtils.getWxCode(response);
    }

    /**
     * 根据获取code的重定向方法 获取openId和access_token
     *
     * @param request
     * @return
     */
    @GetMapping("/getWxgzhUser")
    public R getWxgzhApi(HttpServletRequest request) {
        String code = request.getParameter("code");
        return R.success(wxUtils.getOpenId(code));
    }

    /**
     * 获取用户信息
     * 必须是用户手动授权才可以获取用户信息 否则 无法获取
     *
     * @param openid      用户openid
     * @param accessToken 用户access_token
     * @return
     */
    @GetMapping("/getWxUserInfo")
    public R getWxUserInfo(
            @NotBlank(message = "openid不能为空/空串") String openid
            , @NotBlank(message = "accessToken/空串") String accessToken) {
        return R.success(wxUtils.getUserInfo(openid, accessToken));
    }

}